package com.ruoyi.system.controller;

import cn.hutool.json.JSONArray;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.Dto.TasKConfigDto;
import com.ruoyi.system.Dto.TaskSubDto;
import com.ruoyi.system.Dto.TaskSubDtodate;
import com.ruoyi.system.constant.Constants;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IIbrainTaskService;
import com.ruoyi.system.service.IIbraintasksubExtendService;
import com.ruoyi.system.service.ITaskConfigService;
import com.ruoyi.system.service.ITaskSubService;
//import matlabcontrol.*;
import com.ruoyi.system.utils.frontUtils;
import niftijio.NiftiVolume;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.ruoyi.system.utils.niitobase64;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;



import java.io.*;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.SecureRandom;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static com.ruoyi.system.utils.Util.remaintime;

@RequestMapping("/ibrain")
@RestController
@ControllerAdvice
public class iBrainController extends BaseController {


    private String repath;
    private String basepath;


    @Autowired
    private ITaskConfigService iTaskConfigService;

    @Autowired
    private IIbrainTaskService ibrainTaskService;

    @Autowired
    private ITaskSubService iTaskSubService;

    @Autowired
    private IIbraintasksubExtendService iIbraintasksubExtendService;

    public static String getpurename(boolean one,String input){
        if(one){
            int i1 = input.indexOf("/");
            if(i1==-1)
                i1 = input.indexOf("\\");
            return input.substring(0,i1);
        }
        else {
            int i1 = input.indexOf("/");
            if(i1==-1)
                i1 = input.indexOf("\\");
            int i2 = input.indexOf("/",i1+1);
            if(i2==-1)
                i2 = input.indexOf("\\",i1+1);
            return input.substring(i1+1,i2);
        }
    }

    @Autowired
    public void iBrainController(){

        String firstLine = Constants.pth;

        this.repath = firstLine+File.separator;

        this.basepath = firstLine+File.separator+"test_data"+File.separator;

    }
    public void changefolder(String parentFolderPath,String despath,String T1,String Fun,String name){
        File parentFolder = new File(parentFolderPath);
        if (parentFolder.isDirectory()) {
            File[] subfolders = parentFolder.listFiles(File::isDirectory);
            if (subfolders != null && subfolders.length >= 2) {
                // 比较子文件夹大小
                File largerSubfolder = subfolders[0];
                File smallerSubfolder = subfolders[1];
                if (getFileCount(subfolders[1]) > getFileCount(subfolders[0])) {
                    largerSubfolder = subfolders[1];
                    smallerSubfolder = subfolders[0];
                }

                // 复制文件夹内容到文件夹A
                try {
                    copyFolder(largerSubfolder.getAbsolutePath(),despath+Fun+File.separator+name);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // 复制文件夹内容到文件夹B
                try {
                    copyFolder(smallerSubfolder.getAbsolutePath(),despath+T1+File.separator+name);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // 删除原文件夹
                try {
                    FileUtils.deleteDirectory(parentFolder);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static int getFileCount(File folder) {
        File[] files = folder.listFiles();
        if (files != null) {
            return files.length;
        }
        return 0;
    }
    public static void copyFolder(String sourceFolderPath, String destinationFolderPath) throws IOException {
        File sourceFolder = new File(sourceFolderPath);
        File destinationFolder = new File(destinationFolderPath);

        // 确保源文件夹存在且是一个文件夹
        if (!sourceFolder.exists() || !sourceFolder.isDirectory()) {
            throw new IllegalArgumentException("源文件夹不存在或不是一个文件夹。");
        }

        // 创建目标文件夹
        if (!destinationFolder.exists()) {
            destinationFolder.mkdirs();
        }

        // 遍历源文件夹中的文件和子文件夹
        File[] files = sourceFolder.listFiles();
        if (files != null) {
            for (File file : files) {
                String fileName = file.getName();
                File destinationFile = new File(destinationFolder, fileName);

                // 如果是一个文件，则直接复制
                if (file.isFile()) {
                    Files.copy(file.toPath(), destinationFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                }
                // 如果是一个文件夹，则递归复制
                else if (file.isDirectory()) {
                    copyFolder(file.getAbsolutePath(), destinationFile.getAbsolutePath());
                }
            }
        }
    }
    public static String returnSliceOrder(String SliceOrder){
        String result = "";
        if(SliceOrder.contains(":")||SliceOrder.contains(",")){
            String[] bigparts = SliceOrder.split(",");
            List<String> ls = new ArrayList<>();
            for(String s:bigparts){
                ls.add(s);
            }
            for(String s1:ls){
                String[] parts = s1.split(":");
                int firstTerm = Integer.parseInt(parts[0]);
                int commonDifference = Integer.parseInt(parts[1]);
                int lastTerm = Integer.parseInt(parts[2]);
                int length = (lastTerm - firstTerm) / commonDifference + 1;
                for (int i = 0; i < length; i++) {
                    result=result+ String.valueOf(firstTerm + (i * commonDifference))+" ";
                }
            }
            result = result.substring(0, result.length() - 1);
        }
        else {
            result = SliceOrder;
        }
        return result;
    }
    public static Boolean deleteFile(File file) {
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()) {
            System.out.println("文件删除失败,请检查文件是否存在以及文件路径是否正确");
            return false;
        }
        //获取目录下子文件
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()) {
                //递归删除目录下的文件
                deleteFile(f);
            } else {
                //文件删除
                f.delete();
                //打印文件名
                System.out.println("文件名：" + f.getName());
            }
        }
        //文件夹删除
        file.delete();
        System.out.println("目录名：" + file.getName());
        return true;
    }
    public static List getFolders(String folderPath,List<Subjects> SubList) {
        File folder = new File(folderPath);
        if (folder.isDirectory()) {
            File[] subFolders = folder.listFiles();
            for (File subFolder : subFolders) {
                if (subFolder.isDirectory()) {
                    String result = subFolder.getAbsolutePath().substring(folderPath.length());
                    SubList.add(new Subjects(result));
                }
            }
        }
        return SubList;
    }




    private void addToZipFile(String filePath,String last, ZipOutputStream zos) throws IOException {
        File file = new File(filePath);

        try (InputStream fis = new FileInputStream(file)) {
            ZipEntry zipEntry = new ZipEntry(last+File.separator+file.getName());  // 使用文件名作为ZipEntry的名称
            zos.putNextEntry(zipEntry);

            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zos.write(bytes, 0, length);
            }

            zos.closeEntry();
        }
    }
    //------------------------------------------








    @PostMapping("/delete") //
    public AjaxResult delete(@RequestBody TaskSubDto taskSubDto) {
        IbrainTask ibrainTask = ibrainTaskService.selectIbrainTaskById(taskSubDto.getTaskid());
        String task = ibrainTask.getId().toString()+"_"+ibrainTask.getUserId();
        String contype = "";
        String contypefun = "false";
        String type1 = taskSubDto.getType1();
        if(type1.equals("type1"))
            contype = "T1Raw";
        else
            contype = "T1Img";
        String type2 = taskSubDto.getType2();
        if (type2==null)
            type2="fasle";
        if(type2.equals("type3"))
            contypefun = "FunRaw";
        else if(type2.equals("type4"))
            contypefun = "FunImg";

        String name = iTaskSubService.selectTaskSubById(taskSubDto.getId()).getSubname();
        if(contypefun.equals("false")){
            File file = new File(basepath+task+File.separator+contype+File.separator+name);//输入要删除文件目录的绝对路径
            if (deleteFile(file)) {
                System.out.println("文件删除成功！");
            }
            iTaskSubService.deleteTaskSubById(taskSubDto.getId());
        }else{
            File file1 = new File(basepath+task+File.separator+contype+File.separator+name);//输入要删除文件目录的绝对路径
            if (deleteFile(file1)) {
                System.out.println("T1项删除成功！");
            }
            File file2 = new File(basepath+task+File.separator+contypefun+File.separator+name);//输入要删除文件目录的绝对路径
            if (deleteFile(file2)) {
                System.out.println("BOLD项删除成功！");
            }
            iTaskSubService.deleteTaskSubById(taskSubDto.getId());
        }
        return AjaxResult.success();
    }

    @PostMapping("/batchDelete") //
    public AjaxResult batchDelete(@RequestBody TaskSubDto taskSubDto) {
        IbrainTask ibrainTask = ibrainTaskService.selectIbrainTaskById(taskSubDto.getTaskid());
        String task = ibrainTask.getId().toString()+"_"+ibrainTask.getUserId();
        String contype = "";
        String contypefun = "false";
        String type1 = taskSubDto.getType1();
        if(type1.equals("type1"))
            contype = "T1Raw";
        else
            contype = "T1Img";
        String type2 = taskSubDto.getType2();
        if (type2==null)
            type2="fasle";
        if(type2.equals("type3"))
            contypefun = "FunRaw";
        else if(type2.equals("type4"))
            contypefun = "FunImg";

        int size = taskSubDto.getIds().size();
        Integer[] i = new Integer[size];
        for(int a=0;a<size;a++){
            i[a] = taskSubDto.getIds().get(a);
        }

        if(contypefun.equals("false")){
            for(int l=0;l<i.length;l++){
                String name = iTaskSubService.selectTaskSubById(i[l].longValue()).getSubname();
                File file = new File(basepath+task+File.separator+contype+File.separator+name);//输入要删除文件目录的绝对路径
                if (deleteFile(file)) {
                    System.out.println("文件删除成功！");
                }
            }
            iTaskSubService.deleteTaskSubByIds(i);
        }else{
            for(int l=0;l<i.length;l++){
                String name = iTaskSubService.selectTaskSubById(i[l].longValue()).getSubname();
                File file1 = new File(basepath+task+File.separator+contype+File.separator+name);//输入要删除文件目录的绝对路径
                if (deleteFile(file1)) {
                    System.out.println("T1项删除成功！");
                }
                File file2 = new File(basepath+task+File.separator+contypefun+File.separator+name);//输入要删除文件目录的绝对路径
                if (deleteFile(file2)) {
                    System.out.println("BOLD项删除成功！");
                }
            }
            iTaskSubService.deleteTaskSubByIds(i);
        }
        return AjaxResult.success();
    }


    @PostMapping ("/runmat")   //
    public Map<String, Object> runmat(@RequestBody TasKConfigDto runmatDto){
        Map<String, Object> result = new HashMap<>();
        String type1 = runmatDto.getType1();
        String type2 = runmatDto.getType2();
        String type3 = runmatDto.getIsClinical();
        Long ty3 = 0l;
        if(type3.equals("true"))
            ty3=0l;
        else
            ty3=1l;
        String language = runmatDto.getIsChinese();
        String contype = "";
        String Fun = "";
        int lan = 1;
        if(type1.equals("type1"))
            contype = "T1Raw";
        else
            contype = "T1Img";

        if(language.equals("true"))
            lan = 0;
        else
            lan = 1;
        int size = runmatDto.getIds().size();
        if(size==0){
            result.put("error",1);
            return result;
        }

        Integer[] i = new Integer[size];

        String subjects="";
        for(int a=0;a<size;a++){
            i[a] = runmatDto.getIds().get(a);
            subjects=subjects+iTaskSubService.selectTaskSubById(i[a].longValue()).getSubname()+",";
        }
        subjects = subjects.substring(0,subjects.length()-1);
        if(type2!=null){
            if (type2.equals("type3"))
                Fun = "FunRaw";
            else
                Fun = "FunImg";
            TaskConfig taskConfig = new TaskConfig();
            taskConfig.setTaskid(runmatDto.getTaskid());
            taskConfig.setType1(contype);
            taskConfig.setType2(Fun);
            taskConfig.setLanguage(Long.valueOf(lan));
            taskConfig.setSliceOrder(runmatDto.getSliceOrder());
            taskConfig.setVoxelSize(runmatDto.getVoxelSize());
            taskConfig.setBoundingBox(runmatDto.getBoundingBox());
            taskConfig.setBOLDTR(BigDecimal.valueOf(runmatDto.getBOLDTR()));
            taskConfig.setSkipTR(Long.valueOf(runmatDto.getSkipTR()));
            taskConfig.setRefslic(Long.valueOf(runmatDto.getRefslic()));
            taskConfig.setSmoothFWHM(Long.valueOf(runmatDto.getSmoothFWHM()));
            taskConfig.setFilterLB(BigDecimal.valueOf(runmatDto.getFilterLB()));
            taskConfig.setFilterHB(BigDecimal.valueOf(runmatDto.getFilterHB()));
            taskConfig.setSubject(subjects);
            iTaskConfigService.insertTaskConfig(taskConfig);
        }
        else {
            TaskConfig taskConfig = new TaskConfig();
            taskConfig.setTaskid(runmatDto.getTaskid());
            taskConfig.setType1(contype);
            taskConfig.setClinical(ty3);
            taskConfig.setLanguage(Long.valueOf(lan));
            taskConfig.setSubject(subjects);
            iTaskConfigService.insertTaskConfig(taskConfig);
        }
        ibrainTaskService.updateibraintaskstatus(runmatDto.getTaskid());

        IbrainTask ibrainTask = ibrainTaskService.selectIbrainTaskById(runmatDto.getTaskid());

        boolean isrun = false;
        if(ibrainTask.getStatus()==4)
            isrun = true;
        result.put("isrun",isrun);

        boolean isover = false;
        if(ibrainTask.getStatus()==5)
            isover = true;
        result.put("isover",isover);

        boolean isqueue = false;
        Long numwait = ibrainTask.getQueue();
        if(ibrainTask.getStatus()==1){
            numwait=numwait-1;
            isqueue = true;
        }
        result.put("isqueue",isqueue);
        result.put("numwait",numwait);

        boolean isloading = false;
        if(ibrainTask.getStatus()==2||ibrainTask.getStatus()==3){
            isloading = true;
        }
        result.put("isloading",isloading);
        return result;
    }


    @PostMapping("/progressloader")  //
    public Map<String, Object> progressloader(@RequestBody TaskSubDto taskSubDto) {
        Map<String, Object> result = new HashMap<>();
        IbrainTask ibrainTask = ibrainTaskService.selectIbrainTaskById(taskSubDto.getTaskId());
        TaskConfig taskConfigtemp = new TaskConfig();
        taskConfigtemp.setTaskid(taskSubDto.getTaskId());
        TaskConfig taskConfig = iTaskConfigService.selectTaskConfigNew(taskConfigtemp);


        boolean isrun = false;
        if(ibrainTask.getStatus()==4){
            String time = ibrainTask.getTime();
            long countdown = remaintime(time);
            if(countdown<=0)
                countdown=0;
            result.put("countdown",countdown);
            isrun = true;
        }
        result.put("isrun",isrun);

        boolean isover = false;
        if(ibrainTask.getStatus()==5)
            isover = true;
        result.put("isover",isover);

        boolean isqueue = false;
        Long numwait = ibrainTask.getQueue();
        if(ibrainTask.getStatus()==1){
            numwait=numwait-1;
            isqueue = true;
        }
        result.put("isqueue",isqueue);
        result.put("numwait",numwait);

        boolean isloading = false;
        if(ibrainTask.getStatus()==2||ibrainTask.getStatus()==3){
            isloading = true;
        }
        result.put("isloading",isloading);
        List<TaskSubDto> taskSubDtos = new ArrayList<>();
        List<TaskSub> taskSubs = iTaskSubService.selectTaskSubListBytid(taskSubDto.getTaskId());


        for(TaskSub t:taskSubs){
            TaskSubDto taskSubDto1 = new TaskSubDto();
            if(t.getIsover()==null)
                taskSubDto1.setIsover(false);
            if(t.getIsover()!=null){
                if(t.getIsover()==1)
                    taskSubDto1.setIsover(true);
            }
            if(taskConfig.getType1().equals("T1Raw")&&taskConfig.getType2()==null){
                double p = ((t.getProgress()*1.0)/6)*100;
                DecimalFormat decimalFormat = new DecimalFormat("#.00");
                double resultp = Double.parseDouble(decimalFormat.format(p));
                taskSubDto1.setProgress(BigDecimal.valueOf(resultp));
            }
            if(taskConfig.getType1().equals("T1Img")&&taskConfig.getType2()==null){
                double p = ((t.getProgress()*1.0-1.0)/5)*100;
                if(p<0)
                    p=0.0;
                DecimalFormat decimalFormat = new DecimalFormat("#.00");
                double resultp = Double.parseDouble(decimalFormat.format(p));
                taskSubDto1.setProgress(BigDecimal.valueOf(resultp));
            }
            if(taskConfig.getType1().equals("T1Raw")&&taskConfig.getType2()!=null){
                if(taskConfig.getType2().equals("FunRaw")){
                    double p;
                    if(t.getProgress()>5){
                        p = ((t.getProgress()*1.0-1.0)/16)*100;
                    }
                    else {
                        p = ((t.getProgress()*1.0)/16)*100;
                    }
                    DecimalFormat decimalFormat = new DecimalFormat("#.00");
                    double resultp = Double.parseDouble(decimalFormat.format(p));
                    taskSubDto1.setProgress(BigDecimal.valueOf(resultp));
                }
                if(taskConfig.getType2().equals("FunImg")){
                    double p;
                    if(t.getProgress()>5){
                        p = ((t.getProgress()*1.0-2.0)/15)*100;
                    }
                    else {
                        p = ((t.getProgress()*1.0)/15)*100;
                    }
                    DecimalFormat decimalFormat = new DecimalFormat("#.00");
                    double resultp = Double.parseDouble(decimalFormat.format(p));
                    taskSubDto1.setProgress(BigDecimal.valueOf(resultp));
                }
            }
            if(taskConfig.getType1().equals("T1Img")&&taskConfig.getType2()!=null){
                if(taskConfig.getType2().equals("FunRaw")){
                    double p;
                    if(t.getProgress()>5){
                        p = ((t.getProgress()*1.0-2.0)/15)*100;
                    }
                    else {
                        p = ((t.getProgress()*1.0-1.0)/15)*100;
                    }
                    if(p<0)
                        p=0.0;
                    DecimalFormat decimalFormat = new DecimalFormat("#.00");
                    double resultp = Double.parseDouble(decimalFormat.format(p));
                    taskSubDto1.setProgress(BigDecimal.valueOf(resultp));
                }
                if(taskConfig.getType2().equals("FunImg")){
                    double p;
                    if(t.getProgress()>5){
                        p = ((t.getProgress()*1.0-3.0)/14)*100;
                    }
                    else {
                        p = ((t.getProgress()*1.0-1.0)/14)*100;
                    }
                    if(p<0)
                        p=0.0;
                    DecimalFormat decimalFormat = new DecimalFormat("#.00");
                    double resultp = Double.parseDouble(decimalFormat.format(p));
                    taskSubDto1.setProgress(BigDecimal.valueOf(resultp));
                }
            }
            IbraintasksubExtend ibraintasksubExtend = new IbraintasksubExtend();
            ibraintasksubExtend.setTaskSubId(t.getId());
            List<IbraintasksubExtend> list = iIbraintasksubExtendService.selectIbraintasksubExtendList(ibraintasksubExtend);
            if(!list.isEmpty()){
                taskSubDto1.setSubAge(list.get(0).getSubage());
                taskSubDto1.setSubSex(list.get(0).getSubsex());
            }
            taskSubDto1.setId(t.getId());
            taskSubDto1.setSubname(t.getSubname());
            taskSubDto1.setStatus(t.getStatus());
            taskSubDto1.setStartTime(t.getStartTime());
            taskSubDtos.add(taskSubDto1);
        }
        result.put("userList",taskSubDtos);
        return result;
    }


    @PostMapping("/queueloader")  //
    public Map<String, Object> queueloader(@RequestBody TaskSubDto taskSubDto) {
        Map<String, Object> result = new HashMap<>();
        IbrainTask ibrainTask = ibrainTaskService.selectIbrainTaskById(taskSubDto.getTaskid());
        boolean isrun = false;
        if(ibrainTask.getStatus()==4)
            isrun = true;
        result.put("isrun",isrun);

        boolean isover = false;
        if(ibrainTask.getStatus()==5)
            isover = true;
        result.put("isover",isover);

        boolean isqueue = false;
        Long numwait = ibrainTask.getQueue();
        if(ibrainTask.getStatus()==1){
            numwait=numwait-1;
            isqueue = true;
        }
        result.put("isqueue",isqueue);
        result.put("numwait",numwait);

        boolean isloading = false;
        if(ibrainTask.getStatus()==2||ibrainTask.getStatus()==3){
            isloading = true;
        }
        result.put("isloading",isloading);

        return result;
    }


    @PostMapping("/upload") //
    public Map<String, Object> upload(@RequestParam("file") MultipartFile[] files,@RequestParam("type") String type,@RequestParam("taskid") Long taskid) {
        Map<String, Object> result = new HashMap<>();
        if(files.length < 1) {
            result.put("error","error");
            return result;
        }
        String runpath = "";
        String name = "";
        String contype = "";
        if(type.equals("type1"))
            contype = "T1Raw";
        else
            contype = "T1Img";

        if(type.equals("type1")){
            for(int i=0;i<files.length;i++){
                String temp = files[i].getOriginalFilename();
                if(!temp.substring(temp.length()-4).equals(".dcm")) {
                    result.put("error","error");
                    return result;
                }
            }
        }
        if(type.equals("type2")){
            for(int i=0;i<files.length;i++){
                String temp = files[i].getOriginalFilename();
                if(!temp.substring(temp.length()-4).equals(".nii")) {
                    result.put("error","error");
                    return result;
                }
            }
        }

        boolean foldertype = true;

        int ffcount=0;
        String ff = files[0].getOriginalFilename();
        for (int ffi = 0; ffi < ff.length(); ffi++) {
            char c = ff.charAt(ffi);
            if (c == '/') {
                ffcount++;
            }
        }
        if(ffcount>1)
            foldertype=false;


        List<Subjects> SubListtemp=new ArrayList<>();


        if(foldertype){
            String f = files[0].getOriginalFilename();
            for (int i = 0; i < f.length(); i++) {
                char c = f.charAt(i);
                if (c == '/') {
                    break;
                }
                name += c;
            }
            System.out.println(name);


            //taskid
            IbrainTask ibrainTask = ibrainTaskService.selectIbrainTaskById(taskid);
            String task = ibrainTask.getId().toString()+"_"+ibrainTask.getUserId();
            runpath = basepath+task+File.separator+contype+File.separator;




            File folder = new File(runpath);
            if (!folder.exists()) {
                if (folder.mkdirs()) {
                    System.out.println("Folder created successfully.");
                } else {
                    System.out.println("Failed to create folder.");
                }
            }

            SubListtemp=getFolders(runpath,SubListtemp);
            List<String> SubListtempstring = new ArrayList<>();
            for(Subjects st:SubListtemp){
                SubListtempstring.add(st.getName());
            }

            // 处理文件上传和其他逻辑
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    try {
                        byte[] bytes = file.getBytes();
                        String filePath = runpath + file.getOriginalFilename();
                        String namet = getpurename(true,file.getOriginalFilename());
                        if(SubListtempstring.contains(namet)){
                            result.put("error","error2");
                            List<Subjects> SubList=new ArrayList<>();
                            SubList=getFolders(runpath,SubList);




                            for (Subjects s:SubList){
                                TaskSub taskSub = new TaskSub();
                                taskSub.setTaskId(taskid);
                                taskSub.setSubname(s.getName());



                                List<TaskSub> taskSubs = iTaskSubService.selectTaskSubList(taskSub);
                                if(taskSubs.size()==0||taskSubs==null){
                                    LocalDateTime currentDateTime = LocalDateTime.now();
                                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                    String formattedDateTime = currentDateTime.format(formatter);
                                    taskSub.setStartTime(formattedDateTime);

                                    taskSub.setProgress(0l);
                                    iTaskSubService.insertTaskSub(taskSub);
                                }

                            }
                            List<TaskSub> taskSubs = iTaskSubService.selectTaskSubListBytid(taskid);
                            List<TaskSubDto> taskSubDtos = new ArrayList<>();
                            for (TaskSub taskSub:taskSubs){
                                TaskSubDto taskSubDto = new TaskSubDto();
                                BeanUtils.copyProperties(taskSub,taskSubDto);
                                if(taskSub.getProgress()!=0){
                                    taskSubDto.setProgress(BigDecimal.valueOf(100.0));
                                }
                                else
                                    taskSubDto.setProgress(BigDecimal.valueOf(0.0));
                                if(taskSub.getIsover()!=null&&taskSub.getIsover()==1l)
                                    taskSubDto.setIsover(true);
                                else
                                    taskSubDto.setIsover(false);

                                taskSubDtos.add(taskSubDto);
                            }
                            result.put("userList",taskSubDtos);



                            return result;
                        }

                        File filetemp = new File(filePath);
                        if(!filetemp.exists()){
                            filetemp.getParentFile().mkdir();
                            try {
                                //创建文件
                                filetemp.createNewFile();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
                        bos.write(bytes);
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        else{
            IbrainTask ibrainTask = ibrainTaskService.selectIbrainTaskById(taskid);
            String task = ibrainTask.getId().toString()+"_"+ibrainTask.getUserId();
            runpath = basepath+task+File.separator + contype + File.separator;
            File folder = new File(runpath);
            if (!folder.exists()) {
                if (folder.mkdirs()) {
                    System.out.println("Folder created successfully.");
                } else {
                    System.out.println("Failed to create folder.");
                }
            }
            SubListtemp=getFolders(runpath,SubListtemp);
            List<String> SubListtempstring = new ArrayList<>();
            for(Subjects st:SubListtemp){
                SubListtempstring.add(st.getName());
            }

            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    try {
                        byte[] bytes = file.getBytes();
                        String namet = getpurename(false,file.getOriginalFilename());
                        if(SubListtempstring.contains(namet)){
                            result.put("error","error2");
                            List<Subjects> SubList=new ArrayList<>();
                            SubList=getFolders(runpath,SubList);




                            for (Subjects s:SubList){
                                TaskSub taskSub = new TaskSub();
                                taskSub.setTaskId(taskid);
                                taskSub.setSubname(s.getName());
                                List<TaskSub> taskSubs = iTaskSubService.selectTaskSubList(taskSub);
                                if(taskSubs.size()==0||taskSubs==null){

                                    LocalDateTime currentDateTime = LocalDateTime.now();
                                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                    String formattedDateTime = currentDateTime.format(formatter);
                                    taskSub.setStartTime(formattedDateTime);
                                    taskSub.setProgress(0l);
                                    iTaskSubService.insertTaskSub(taskSub);
                                }

                            }
                            List<TaskSub> taskSubs = iTaskSubService.selectTaskSubListBytid(taskid);
                            List<TaskSubDto> taskSubDtos = new ArrayList<>();
                            for (TaskSub taskSub:taskSubs){
                                TaskSubDto taskSubDto = new TaskSubDto();
                                BeanUtils.copyProperties(taskSub,taskSubDto);
                                if(taskSub.getProgress()!=0){
                                    taskSubDto.setProgress(BigDecimal.valueOf(100.0));
                                }
                                else
                                    taskSubDto.setProgress(BigDecimal.valueOf(0.0));
                                if(taskSub.getIsover()!=null&&taskSub.getIsover()==1l)
                                    taskSubDto.setIsover(true);
                                else
                                    taskSubDto.setIsover(false);

                                taskSubDtos.add(taskSubDto);
                            }
                            result.put("userList",taskSubDtos);



                            return result;
                        }
                        String filenamepath = file.getOriginalFilename();
                        int index = filenamepath.indexOf('/');
                        String afterpath = task + File.separator + contype + File.separator + filenamepath.substring(index + 1);
                        String filePath = basepath + afterpath;
                        File filetemp = new File(filePath);
                        if(!filetemp.exists()){
                            filetemp.getParentFile().mkdir();
                            try {
                                //创建文件
                                filetemp.createNewFile();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
                        bos.write(bytes);
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        List<Subjects> SubList=new ArrayList<>();
        SubList=getFolders(runpath,SubList);




        for (Subjects s:SubList){
            TaskSub taskSub = new TaskSub();
            taskSub.setTaskId(taskid);
            taskSub.setSubname(s.getName());
            List<TaskSub> taskSubs = iTaskSubService.selectTaskSubList(taskSub);
            if(taskSubs.size()==0||taskSubs==null){
                LocalDateTime currentDateTime = LocalDateTime.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedDateTime = currentDateTime.format(formatter);
                taskSub.setStartTime(formattedDateTime);
                taskSub.setProgress(0l);
                iTaskSubService.insertTaskSub(taskSub);
            }
        }
        List<TaskSub> taskSubs = iTaskSubService.selectTaskSubListBytid(taskid);
        List<TaskSubDto> taskSubDtos = new ArrayList<>();
        for (TaskSub taskSub:taskSubs){
            TaskSubDto taskSubDto = new TaskSubDto();
            BeanUtils.copyProperties(taskSub,taskSubDto);
            if(taskSub.getProgress()!=0){
                taskSubDto.setProgress(BigDecimal.valueOf(100.0));
            }
            else
                taskSubDto.setProgress(BigDecimal.valueOf(0.0));
            if(taskSub.getIsover()!=null&&taskSub.getIsover()==1l)
                taskSubDto.setIsover(true);
            else
                taskSubDto.setIsover(false);
            taskSubDtos.add(taskSubDto);
        }
        result.put("userList",taskSubDtos);
        return result;
    }

    @PostMapping("/getaskid") //
    public Map<String,Object> getaskid(){
        Map<String, Object> result = new HashMap<>();
        IbrainTask ibrainTask= ibrainTaskService.gettaskid();
        result.put("taskid",ibrainTask.getId());

        boolean isrun = false;
        if(ibrainTask.getStatus()==4)
            isrun = true;
        result.put("isrun",isrun);

        boolean isover = false;
        if(ibrainTask.getStatus()==5)
            isover = true;
        result.put("isover",isover);

        boolean isqueue = false;
        Long numwait = ibrainTask.getQueue();
        if(ibrainTask.getStatus()==1){
            numwait=numwait-1;
            isqueue = true;
        }
        result.put("isqueue",isqueue);
        result.put("numwait",numwait);

        boolean isloading = false;
        if(ibrainTask.getStatus()==2||ibrainTask.getStatus()==3){
            isloading = true;
        }
        result.put("isloading",isloading);

        return result;
    }


    @PostMapping("/getuserlist") //
    public Map<String,Object> getuserlist(@RequestBody TaskSub taskSub){
        Map<String, Object> result = new HashMap<>();
        List<TaskSub> taskSubs = iTaskSubService.selectTaskSubListBytid(taskSub.getTaskId());
        List<TaskSubDto> taskSubDtos = new ArrayList<>();
        TaskConfig taskConfigtemp = new TaskConfig();
        taskConfigtemp.setTaskid(taskSub.getTaskId());
        TaskConfig taskConfig2 = iTaskConfigService.selectTaskConfigNew(taskConfigtemp);
        IbrainTask ibt = ibrainTaskService.selectIbrainTaskById(taskSub.getTaskId());
        if(taskConfig2!=null&&(ibt.getStatus()==4||ibt.getStatus()==5)){
            if(ibt.getStatus()==4){
                String time = ibt.getTime();
                long countdown = remaintime(time);
                if(countdown<=0)
                    countdown=0;
                result.put("countdown",countdown);
            }


            TaskConfig taskConfig = iTaskConfigService.selectTaskConfigNew(taskConfigtemp);
            for(TaskSub t:taskSubs){
                TaskSubDto taskSubDto1 = new TaskSubDto();
                if(t.getIsover()==null)
                    taskSubDto1.setIsover(false);
                if(t.getIsover()!=null){
                    if(t.getIsover()==1)
                        taskSubDto1.setIsover(true);
                }
                if(taskConfig.getType1().equals("T1Raw")&&taskConfig.getType2()==null){
                    double p = ((t.getProgress()*1.0)/6)*100;
                    DecimalFormat decimalFormat = new DecimalFormat("#.00");
                    double resultp = Double.parseDouble(decimalFormat.format(p));
                    taskSubDto1.setProgress(BigDecimal.valueOf(resultp));
                }
                if(taskConfig.getType1().equals("T1Img")&&taskConfig.getType2()==null){
                    double p = ((t.getProgress()*1.0-1.0)/5)*100;
                    if(p<0)
                        p=0.0;
                    DecimalFormat decimalFormat = new DecimalFormat("#.00");
                    double resultp = Double.parseDouble(decimalFormat.format(p));
                    taskSubDto1.setProgress(BigDecimal.valueOf(resultp));
                }
                if(taskConfig.getType1().equals("T1Raw")&&taskConfig.getType2()!=null){
                    if(taskConfig.getType2().equals("FunRaw")){
                        double p;
                        if(t.getProgress()>5){
                            p = ((t.getProgress()*1.0-1.0)/16)*100;
                        }
                        else {
                            p = ((t.getProgress()*1.0)/16)*100;
                        }
                        DecimalFormat decimalFormat = new DecimalFormat("#.00");
                        double resultp = Double.parseDouble(decimalFormat.format(p));
                        taskSubDto1.setProgress(BigDecimal.valueOf(resultp));
                    }
                    if(taskConfig.getType2().equals("FunImg")&&taskConfig.getType2()!=null){
                        double p;
                        if(t.getProgress()>5){
                            p = ((t.getProgress()*1.0-2.0)/15)*100;
                        }
                        else {
                            p = ((t.getProgress()*1.0)/15)*100;
                        }
                        DecimalFormat decimalFormat = new DecimalFormat("#.00");
                        double resultp = Double.parseDouble(decimalFormat.format(p));
                        taskSubDto1.setProgress(BigDecimal.valueOf(resultp));
                    }
                }
                if(taskConfig.getType1().equals("T1Img")&&taskConfig.getType2()!=null){
                    if(taskConfig.getType2().equals("FunRaw")){
                        double p;
                        if(t.getProgress()>5){
                            p = ((t.getProgress()*1.0-2.0)/15)*100;
                        }
                        else {
                            p = ((t.getProgress()*1.0-1.0)/15)*100;
                        }
                        if(p<0)
                            p=0.0;
                        DecimalFormat decimalFormat = new DecimalFormat("#.00");
                        double resultp = Double.parseDouble(decimalFormat.format(p));
                        taskSubDto1.setProgress(BigDecimal.valueOf(resultp));
                    }
                    if(taskConfig.getType2().equals("FunImg")){
                        double p;
                        if(t.getProgress()>5){
                            p = ((t.getProgress()*1.0-3.0)/14)*100;
                        }
                        else {
                            p = ((t.getProgress()*1.0-1.0)/14)*100;
                        }
                        if(p<0)
                            p=0.0;
                        DecimalFormat decimalFormat = new DecimalFormat("#.00");
                        double resultp = Double.parseDouble(decimalFormat.format(p));
                        taskSubDto1.setProgress(BigDecimal.valueOf(resultp));
                    }
                }
                IbraintasksubExtend ibraintasksubExtend = new IbraintasksubExtend();
                ibraintasksubExtend.setTaskSubId(t.getId());
                List<IbraintasksubExtend> list = iIbraintasksubExtendService.selectIbraintasksubExtendList(ibraintasksubExtend);
                if(!list.isEmpty()){
                    taskSubDto1.setSubAge(list.get(0).getSubage());
                    taskSubDto1.setSubSex(list.get(0).getSubsex());
                }
                taskSubDto1.setId(t.getId());
                taskSubDto1.setSubname(t.getSubname());
                taskSubDto1.setStatus(t.getStatus());
                taskSubDto1.setStartTime(t.getStartTime());
                taskSubDtos.add(taskSubDto1);
            }
            result.put("userList",taskSubDtos);
            return result;
        }
        for(TaskSub t:taskSubs){
            TaskSubDto taskSubDto2 = new TaskSubDto();
            IbraintasksubExtend ibraintasksubExtend = new IbraintasksubExtend();
            ibraintasksubExtend.setTaskSubId(t.getId());
            List<IbraintasksubExtend> list = iIbraintasksubExtendService.selectIbraintasksubExtendList(ibraintasksubExtend);
            if(!list.isEmpty()){
                taskSubDto2.setSubAge(list.get(0).getSubage());
                taskSubDto2.setSubSex(list.get(0).getSubsex());
            }
            taskSubDto2.setId(t.getId());
            taskSubDto2.setSubname(t.getSubname());
            taskSubDto2.setStatus(t.getStatus());
            taskSubDto2.setStartTime(t.getStartTime());
            if(taskSub.getProgress()==null){
                BigDecimal prog =  new BigDecimal("0");
                taskSubDto2.setProgress(prog);
            }
            taskSubDtos.add(taskSubDto2);
        }
        result.put("userList",taskSubDtos);
        return result;
    }

    @PostMapping("/upload_complex") //x
    public Map<String, Object> upload_complex(@RequestParam("file") MultipartFile[] files,@RequestParam("type1") String type1,@RequestParam("type2") String type2,@RequestParam("taskid") Long taskid) {
        Map<String, Object> result = new HashMap<>();
        if(files.length < 1) {
            result.put("error","error");
            return result;
        }
        System.out.println("---------------------");


        List<Subjects> subjectsList = new ArrayList<>();

        IbrainTask ibrainTask = ibrainTaskService.selectIbrainTaskById(taskid);
        String task = ibrainTask.getId().toString()+"_"+ibrainTask.getUserId();




        int ffcount=0;
        String ff = files[0].getOriginalFilename();
        for (int ffi = 0; ffi < ff.length(); ffi++) {
            char c = ff.charAt(ffi);
            if (c == '/') {
                ffcount++;
            }
        }


        if(type1.equals("type1")&&type2.equals("type3")){
            for(int i=0;i<files.length;i++){
                String temp = files[i].getOriginalFilename();
                if(!temp.substring(temp.length()-4).equals(".dcm")) {
                    result.put("error","error");
                    return result;
                }
            }
        }


        if(type1.equals("type2")&&type2.equals("type4")){
            for(int i=0;i<files.length;i++){
                String temp = files[i].getOriginalFilename();
                if(!temp.substring(temp.length()-4).equals(".nii")) {
                    result.put("error","error");
                    return result;
                }
            }
        }

        //t1 fun
        if(type1.equals("type1")&&type2.equals("type4")){
            for(int i=0;i<files.length;i++){
                String temp = files[i].getOriginalFilename();
                if(!((temp.substring(temp.length()-4).equals(".nii"))||temp.substring(temp.length()-4).equals(".dcm"))) {
                    result.put("error","error");
                    return result;
                }
            }
        }

        //t1 fun
        if(type1.equals("type2")&&type2.equals("type3")){
            for(int i=0;i<files.length;i++){
                String temp = files[i].getOriginalFilename();
                if(!((temp.substring(temp.length()-4).equals(".nii"))||temp.substring(temp.length()-4).equals(".dcm"))) {
                    result.put("error","error");
                    return result;
                }
            }
        }

        String contype = "";
        if(type1.equals("type1"))
            contype="T1Raw";
        else
            contype="T1Img";




        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();

                    String filenamepath = file.getOriginalFilename();
                    int index = filenamepath.indexOf('/');
                    String afterpath = "";
                    if(ffcount>2){
                        afterpath = task + File.separator + "temp" + File.separator + filenamepath.substring(index + 1);
                    }
                    else{
                        afterpath = task + File.separator + "temp" + File.separator + filenamepath;
                    }

                    String filePath = basepath + afterpath;


                    File filetemp = new File(filePath);
                    if(!filetemp.exists()){
                        filetemp.getParentFile().mkdirs();
                        try {
                            //创建文件
                            filetemp.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
                    bos.write(bytes);
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String T1 = "";
        String Fun = "";
        String tempath = basepath+task+File.separator+"temp"+File.separator;
        subjectsList=getFolders(tempath,subjectsList); //用户列表------------------------
        if(type1.equals("type1")){
            T1 = "T1Raw";
            File t1file = new File(tempath+"T1Raw");
            t1file.mkdirs();
            for(Subjects subjects:subjectsList){
                File namefile = new File(tempath+"T1Raw"+File.separator+subjects.getName());
                namefile.mkdirs();
            }
        }
        else {
            T1 = "T1Img";
            File t1file = new File(tempath+"T1Img");
            t1file.mkdirs();
            for(Subjects subjects:subjectsList){
                File namefile = new File(tempath+"T1Img"+File.separator+subjects.getName());
                namefile.mkdirs();
            }
        }
        if(type2.equals("type3")) {
            Fun = "FunRaw";
            File funfile = new File(tempath + "FunRaw");
            funfile.mkdirs();
            for(Subjects subjects:subjectsList){
                File namefile = new File(tempath +"FunRaw"+File.separator+subjects.getName());
                namefile.mkdirs();
            }
        }
        else {
            Fun = "FunImg";
            File funfile = new File(tempath + "FunImg");
            funfile.mkdirs();
            for(Subjects subjects:subjectsList){
                File namefile = new File(tempath +"FunImg"+File.separator+subjects.getName());
                namefile.mkdirs();
            }
        }
        for(Subjects subjects:subjectsList){
            changefolder(tempath+subjects.getName(),basepath+task+File.separator,T1,Fun,subjects.getName());
        }
        File filetemp = new File(basepath+task+File.separator+"temp");//输入要删除文件目录的绝对路径
        if (deleteFile(filetemp)) {
            System.out.println("文件夹temp删除成功！");
        }
        int num = subjectsList.size();


        for (Subjects s:subjectsList){
            TaskSub taskSub = new TaskSub();
            taskSub.setTaskId(taskid);
            taskSub.setSubname(s.getName());


            List<TaskSub> taskSubs = iTaskSubService.selectTaskSubList(taskSub);
            if(taskSubs.size()==0||taskSubs==null){
                LocalDateTime currentDateTime = LocalDateTime.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedDateTime = currentDateTime.format(formatter);
                taskSub.setStartTime(formattedDateTime);
                taskSub.setProgress(0l);
                iTaskSubService.insertTaskSub(taskSub);
            }
        }
        List<TaskSub> taskSubs = iTaskSubService.selectTaskSubListBytid(taskid);
        List<TaskSubDto> taskSubDtos = new ArrayList<>();
        for (TaskSub taskSub:taskSubs){
            TaskSubDto taskSubDto = new TaskSubDto();
            BeanUtils.copyProperties(taskSub,taskSubDto);
            if(taskSub.getProgress()!=0){
                taskSubDto.setProgress(BigDecimal.valueOf(100.0));
            }
            else
                taskSubDto.setProgress(BigDecimal.valueOf(0.0));
            taskSubDtos.add(taskSubDto);
        }
        result.put("userList",taskSubDtos);

        return result;
    }


    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam Integer taskid,@RequestParam String name) throws IOException {
        String dir="";
        IbrainTask ibrainTask = ibrainTaskService.selectIbrainTaskById(Long.valueOf(taskid));
        String filename = name+"_report.docx";
            dir = basepath+taskid+"_"+ibrainTask.getUserId()+File.separator+"Results"+File.separator+name;
        Path filePath = Paths.get(dir,filename);
        File file = filePath.toFile();
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    }


    @PostMapping("/downloadreportlist")
    public ResponseEntity<InputStreamResource> downloadreportlist(@RequestBody TaskSubDto taskSubDto) throws IOException {
        int size = taskSubDto.getIds().size();
        Map<String,String> pthmap = new HashMap<>();
        for(int a=0;a<size;a++){
            TaskSub taskSub = iTaskSubService.selectTaskSubById(taskSubDto.getIds().get(a).longValue());
            Long uid = ibrainTaskService.getuidbytaskid(taskSub.getTaskId());
            String pth = basepath+taskSub.getTaskId()+"_"+uid+File.separator+"Results"+File.separator+taskSub.getSubname()+File.separator+taskSub.getSubname()+"_report.docx";
            pthmap.put(pth,taskSub.getStartTime());
        }
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ZipOutputStream zos = new ZipOutputStream(baos)) {
            for (Map.Entry<String, String> entry : pthmap.entrySet()){
                addToZipFile(entry.getKey(),entry.getValue(),zos);
            }
            zos.close();
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_TYPE, "application/zip");
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=files.zip");
            InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(baos.toByteArray()));
            return new ResponseEntity<>(resource, headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @PostMapping("/reinput")
    public Map<String,Object> reinput(){
        Map<String, Object> result = new HashMap<>();
        ibrainTaskService.reload();
        result.put("success","success");
        return result;
    }

    @GetMapping("/downloadlist")
    public Map<String,Object> downloadlist(){
        Map<String, Object> result = new HashMap<>();
        List<TaskSubDto> taskSubDtos = new ArrayList<>();
        taskSubDtos = ibrainTaskService.getdownloadsub();
        result.put("userList",taskSubDtos);
        return result;
    }


    @PostMapping("/downloadlistbysearch")
    public Map<String,Object> downloadlistbysearch(@RequestBody TaskSubDtodate taskSubDto){
        Map<String, Object> result = new HashMap<>();
        TaskSubDto1 taskSubDto1 = new TaskSubDto1();
        if(taskSubDto.getEndTime()!=null){
            taskSubDto1.setEndTime_s(taskSubDto.getEndTime().get(0).substring(0,10));
            taskSubDto1.setEndTime_e(taskSubDto.getEndTime().get(1).substring(0,10));
        }
        if(taskSubDto.getStartTime()!=null){
            taskSubDto1.setStartTime_s(taskSubDto.getStartTime().get(0).substring(0,10));
            taskSubDto1.setStartTime_e(taskSubDto.getStartTime().get(1).substring(0,10));
        }
        if(taskSubDto.getSubname()!=null){
            taskSubDto1.setSubname(taskSubDto.getSubname());
        }
        List<TaskSubDto> taskSubDtos = new ArrayList<>();
        taskSubDtos = ibrainTaskService.getdownloadsubbysearch(taskSubDto1);
        result.put("userList",taskSubDtos);
        return result;
    }






    //todo 可视化脑图debug

    @GetMapping("/getniixyz")
    public Map<String,Object> getniixyz(@RequestParam int x,@RequestParam int y,@RequestParam int z,@RequestParam Long id,@RequestParam String name){
        Map<String,Object> result = new HashMap<>();
        TaskSub taskSub = iTaskSubService.selectTaskSubById(id);
        IbrainTask ibrainTask = ibrainTaskService.selectIbrainTaskById(taskSub.getTaskId());
        String pth = Constants.pth+File.separator+"test_data"+File.separator+ibrainTask.getId()+"_"+ibrainTask.getUserId()+File.separator+"T1Img"+File.separator+name+File.separator+name+".nii";
        String[] res = new String[3];
        res = niitobase64.getbase64(pth,x,y,z);
        result.put("x",res[0]);
        result.put("y",res[1]);
        result.put("z",res[2]);
        return result;
    }

    @GetMapping("getxyzlen")
    public Map<String,Object> getxyzlen(@RequestParam Long id,@RequestParam String name){
        Map<String,Object> result = new HashMap<>();
        TaskSub taskSub = iTaskSubService.selectTaskSubById(id);
        IbrainTask ibrainTask = ibrainTaskService.selectIbrainTaskById(taskSub.getTaskId());
        String pth = Constants.pth+File.separator+"test_data"+File.separator+ibrainTask.getId()+"_"+ibrainTask.getUserId()+File.separator+"T1Img"+File.separator+name+File.separator+name+".nii";
        int[] res = new int[3];
        res = niitobase64.getbase64len(pth);
        result.put("x",res[0]-1);
        result.put("y",res[1]-1);
        result.put("z",res[2]-1);
        return result;
    }



    @GetMapping("/testibrain")
    public Map<String,Object> testibrain(){
        Map<String,Object> result = new HashMap<>();
        result.put("result","result");
        return result;
    }





    @GetMapping("/getnii") // Added by WANG RUOZHU
    public Map<String,Object> getnii(@RequestParam Long id, @RequestParam String name){
        TaskSub taskSub = iTaskSubService.selectTaskSubById(id);
        IbrainTask ibrainTask = ibrainTaskService.selectIbrainTaskById(taskSub.getTaskId());
        String pth = Constants.pth+File.separator+"test_data"+File.separator+ibrainTask.getId()+"_"+ibrainTask.getUserId()+File.separator+"T1Img"+File.separator+name+File.separator+name+".nii";
        try{
            NiftiVolume volume = NiftiVolume.read(pth);
            Map<String,Object> ans = new HashMap<>();

            ans.put("header", volume.header);
            ans.put("data", frontUtils.nii2array(volume));
            return ans;
        } catch (IOException e){
            e.printStackTrace();
            return null;
        }
    }

    //--

    @PostMapping("/updateAge")
    public Map<String,Object> updateAge(@RequestBody IbraintasksubExtend ibraintasksubExtend){
        Map<String,Object> result = new HashMap<>();
        IbraintasksubExtend ibraintasksubExtendsear = new IbraintasksubExtend();
        ibraintasksubExtendsear.setTaskSubId(ibraintasksubExtend.getTaskSubId());
        List<IbraintasksubExtend> list = iIbraintasksubExtendService.selectIbraintasksubExtendList(ibraintasksubExtendsear);
        if(list.size()==0||list==null){
            iIbraintasksubExtendService.insertIbraintasksubExtend(ibraintasksubExtend);
        }
        else{
            IbraintasksubExtend ibraintasksubExtendtemp = list.get(0);
            ibraintasksubExtendtemp.setSubage(ibraintasksubExtend.getSubage());
            iIbraintasksubExtendService.updateIbraintasksubExtend(ibraintasksubExtendtemp);
        }
        result.put("result","result");
        return result;
    }

    @PostMapping("/updateSex")
    public Map<String,Object> updateSex(@RequestBody IbraintasksubExtend ibraintasksubExtend){
        Map<String,Object> result = new HashMap<>();
        IbraintasksubExtend ibraintasksubExtendsear = new IbraintasksubExtend();
        ibraintasksubExtendsear.setTaskSubId(ibraintasksubExtend.getTaskSubId());
        List<IbraintasksubExtend> list = iIbraintasksubExtendService.selectIbraintasksubExtendList(ibraintasksubExtendsear);
        if(list.size()==0||list==null){
            iIbraintasksubExtendService.insertIbraintasksubExtend(ibraintasksubExtend);
        }
        else{
            IbraintasksubExtend ibraintasksubExtendtemp = list.get(0);
            ibraintasksubExtendtemp.setSubsex(ibraintasksubExtend.getSubsex());
            iIbraintasksubExtendService.updateIbraintasksubExtend(ibraintasksubExtendtemp);
        }
        result.put("result","result");
        return result;
    }

}

